package cn.wzx.controller;

import cn.wzx.entity.Hot;
import cn.wzx.entity.Largefile;
import cn.wzx.respJson.RespJson;
import cn.wzx.service.HotService;
import cn.wzx.service.LargefileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;

@CrossOrigin // 允许跨域访问
@Controller
@RequestMapping("/api/adm/hot")
public class HotController {
    @Autowired
    HotService hotService;

    @Autowired
    LargefileService largefileService;

    // 热点全查询
    @ResponseBody
    @RequestMapping("/findAll")
    public Map<String,Object> findAll(){
        return RespJson.pack(200,"添加成功",hotService.findAll());
    }

    // 热点根据ID删除
    @ResponseBody
    @RequestMapping("/delete/{id}")
    public Map<String,Object> delete(@PathVariable("id") Integer id){
        hotService.delete(id);
        return RespJson.pack(200,"删除成功",null);
    }

    // 添加热点
    @ResponseBody
    @RequestMapping("/addHot")
    public Map<String,Object> addHot(Hot hot, Largefile largefile, @RequestParam(value = "pic",required = false) MultipartFile file){
        System.out.println(hot);
        System.out.println(file);
        if (file == null || hot.getMemo().length() < 6) {
            return RespJson.pack(500,"图片未上传或描述太短",null);
        }
        if (file != null && file.getSize()>0){
            try {
                String newName = UUID.randomUUID().toString();
                hot.setPicture(newName);
                largefile.setId(hot.getPicture());
                largefile.setFilename(file.getOriginalFilename());
                byte[] fileBytes = file.getBytes();
                largefile.setContent(fileBytes);
                largefileService.add(largefile);

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        hotService.addHot(hot);
        return RespJson.pack(200,"添加成功",hot);
    }
}
